import { useEffect, useRef, useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import request from 'umi-request';
import { Button, message, Upload } from 'antd';
import { baseUrl } from '@/utils/requestConfig'
import { downloadFile } from '@/services/project';
import styles from './index.less';


const { NODE_ENV } = process.env;
const UploadFile = (props) => {
  const [fileList, setFileList] = useState([])
  const [cacheFileList, setCacheFileList] = useState([])
  const { value = [], edit = false, onChange = () => {}, disabled} = props;
  useEffect(()=>{
    if(edit && value.length > 0) {
      setFileList(value)
      props.onChange(value)
    }
  },[value])
  const uploadProps = {
    name: 'file',
    action: baseUrl + '/upload',
    headers: {
      accessToken: localStorage.getItem('token_umi_app'),
    },
    showUploadList:{   
      showRemoveIcon:true,
      showDownloadIcon:true,
    },
    onChange(info) {
      let newFileList = info.fileList.map((item)=>{
        let newId = item.response?.id;
        if(!newId && info.file.status !== 'uploading') {
          const uidList = cacheFileList.map(val=> val.uid);
          let index = uidList.indexOf(item.uid);
          newId = cacheFileList[index].id
        }
        return {
          uid: item.uid,
          status: item.status,
          name: item.name,
          url: item.response?.url,
          id: newId,
        }
      });
            
      setFileList(JSON.parse(JSON.stringify(newFileList)) || [])
      props.onChange(newFileList || [])
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
        setCacheFileList(JSON.parse(JSON.stringify(newFileList)) || [])
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    onDownload(info){
        request(`${baseUrl}/download/${info.id}`, {
          method: 'GET',
          responseType: 'blob',
        }).then(res => {
          const blob = new Blob([res]);
          const objectURL = URL.createObjectURL(blob);
          let btn = document.createElement('a');
          btn.download = info.name;
          btn.href = objectURL;
          btn.click();
          URL.revokeObjectURL(objectURL);
          btn = null;
        });
    },
    progress: {
      strokeColor: {
        '0%': '#108ee9',
        '100%': '#87d068',
      },
      strokeWidth: 3,
      format: (percent) => percent && `${parseFloat(percent.toFixed(2))}%`,
    },
  }

  
  return (
    <div className={styles.tableWrap}>
      <Upload {...uploadProps} fileList={fileList}>
         <Button icon={<UploadOutlined />} disabled={disabled} size='small' type='primary'>上传附件</Button>
      </Upload>
    </div>
  )
}

export default UploadFile